import React from 'react';
import styles from './index.less';
import { Spin, Space, Button, DatePicker, Row, Col } from 'antd';
import moment from 'moment';

import { TRMessage } from '#/components';
import { UploadOutlined } from '#/utils/antdIcons';

import { export_json_to_excel } from '@/utils/fileExport';
import { useTRState, TjSelect } from '@/pages/ETrade/components';

import { getSpotPriceDifferencePriceForecast } from '../services';
import { Chart1, Chart2 } from './charts';
import PriceDirection from './components/PriceDirection';
import { expCodes1, expCodes2, expCodes3 } from './helper';

const defaultForm = (power) => {
  const stations = power?.[0]?.children || [];
  const dates = [moment().add(1, 'days'), moment().add(3, 'days')];
  return {
    stations,
    dates,
    marketId: power?.[0]?.value || null,
    provinceId: power?.[0]?.provinceId || null,
    stationItem: stations?.[0] || null,
    version: 1,
  };
};

export default ({ power, buttonPermissions }) => {
  const exportKey = 'SpotPriceDiffForecast-export';
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    // 表单
    ...defaultForm(power),
    // 数据
    chart1: [],
    chart2: [],
    chart3: [],
    loading: true,
    exporter: {}, // 导出文件名称
  });

  React.useEffect(() => {
    _onFinish();
  }, [state.version]);

  const fetch = async (params) => {
    setState({ loading: true });
    const res = await getSpotPriceDifferencePriceForecast(params);
    const chart1 = fmtData(res?.spotPriceDataMap?.clearDifferencePriceForecast);
    const chart2 = fmtData(res?.spotPriceDataMap?.transitionPriceDifferenceForecast);
    const chart3 = fmtData(res?.spotPriceDataMap?.spreadDirectionPrediction);

    setState({
      chart1,
      chart2,
      chart3,
      loading: false,
    });
  };

  /** methods */
  const fmtData = (_obj) => {
    // 数据处理JSON
    const keys = Object.keys(_obj || {});
    if (!keys.length) return [];
    let result = {};
    const radioKeys = [
      'priceDifferenceConfidence',
      'baseRatio',
      'baseRatioForecast',
      'differencePriceConfidenceTransition',
      'foreDiffProb',
    ];
    for (const k in _obj) {
      const dayMap = _obj[k] || {};
      for (const day in dayMap) {
        const timeMap = dayMap[day] || {};
        const dd = day.replace(/[-]/g, '');
        for (const time in timeMap) {
          const val = timeMap[time];
          if (radioKeys.includes(k)) {
            // 百分比处理
            val = Math.round(val * 100 || 0);
          }
          const id = `${dd} ${time.replace(':', '')}`; // YYYYMMDD HHmm
          if (!result[id]) result[id] = { id };
          result[id][k] = val;
        }
      }
    }
    return Object.values(result);
  };

  const onChangeRegion = (region) => {
    // 改变省份
    const provinceId = region.provinceId;
    const marketId = region.value;
    const stations = region?.children || [];
    const stationItem = stations?.[0] || null;
    setState({
      provinceId,
      marketId,
      stations,
      stationItem,
    });
  };

  const _onFinish = () => {
    // 查询
    const { provinceId, stationItem, dates, version } = state;
    const formValues = {
      provinceId,
      stationId: stationItem.value,
      startDate: dates[0].format('YYYY-MM-DD'),
      endDate: dates[1].format('YYYY-MM-DD'),
      version,
    };
    setState({
      exporter: {
        staitonName: stationItem.label,
        dateRange: `${dates[0].format('YYYYMMDD')}-${dates[1].format('YYYYMMDD')}`,
      },
    });
    fetch(formValues);
  };

  const _onReset = () => {
    // 重置
    const _def = defaultForm(power);
    state.dates = _def.dates;
    state.provinceId = _def.provinceId;
    state.marketId = _def.marketId;
    state.stationItem = _def.stationItem;
    state.version = _def.version;
    setState({
      ..._def,
    });
    _onFinish();
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    const { chart1, chart2, chart3 } = state;
    const { staitonName, dateRange } = state.exporter;
    // 翻转数据
    const getExpData = (data, dims) =>
      dims.map(({ code, name }) => [name, ...data.map((x) => x[code])]);

    const params = {
      filename: `${staitonName}-${dateRange}-价差预测`,
      header: [`${staitonName} 实时-日前出清价差预测`, dateRange, '单位：元/MWh'],
      data: [
        ...getExpData(chart1, expCodes1),
        [],
        [`${staitonName} 实时-日前出清价差方向预测`, dateRange, '单位：元/MWh'],
        ...getExpData(chart3, expCodes3(state.version)),
        [],
        [`${staitonName} 实时出清-日前过渡价差预测`, dateRange, '单位：元/MWh'],
        ...getExpData(chart2, expCodes2),
      ],
      autoWidth: false,
    };
    export_json_to_excel(params);
  };

  const changePriceDirection = (version) => {
    setState({ version });
  };

  /** render */
  const _renderMain = () => {
    if (state.loading) return null;
    return (
      <Row gutter={[24, 24]}>
        <Col span={12}>
          <Chart1 data={state.chart1} />
        </Col>
        <Col span={12}>
          <PriceDirection
            version={state.version}
            onChange={changePriceDirection}
            data={state.chart3}
          />
        </Col>
        <Col span={24}>
          <Chart2 data={state.chart2} />
        </Col>
      </Row>
    );
  };
  return (
    <Spin spinning={state.loading}>
      <div className={styles.head}>
        <Space size={16} wrap>
          <TjSelect
            style={{ width: 200 }}
            value={state.marketId}
            options={power}
            showSearch
            onChange={(v, opt) => onChangeRegion(opt)}
          />
          <TjSelect
            style={{ width: 200 }}
            value={state.stationItem?.value}
            options={state.stations}
            showSearch
            onChange={(v, stationItem) => setState({ stationItem })}
          />
          <DatePicker.RangePicker
            style={{ width: 260 }}
            value={state.dates}
            separator="-"
            format={'YYYYMMDD'}
            allowClear={false}
            onChange={(dates) => setState({ dates })}
            getPopupContainer={(e) => e.parentNode}
          />
          <Space size={16}>
            <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
            <Button type="link" icon={<UploadOutlined />} onClick={_onExport}>
              导出
            </Button>
          </Space>
        </Space>
      </div>
      <div className={styles.main}>{_renderMain()}</div>
    </Spin>
  );
};
